package com.scalar.chiptrack.operations.reports.actionCommands;

import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.finance.dao.UpdateViewCostDAO;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.ScalarException;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.ArrayList;

/**
 * User: KP
 * Date: Oct 25, 2006
 * Time: 2:08:54 PM
*/
public class DataDumpReportSearchActionCommand extends ActionCommand
{
    public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
    {
        String action       = request.getParameter( "action" );
        String reportType   = request.getParameter( "reportType" );
        String forward      = "success";

        HashMap info 	= new HashMap();
        HashMap errors  = new HashMap();

        if( DUMP_REPORT_INVENTORY_COST_SEARCH_ACTION.equalsIgnoreCase( action ) || ACTION_CALCULATE_COST.equalsIgnoreCase( action ) )
        {
            ArrayList baseProductsList = ProductDao.loadChipBaseProducts( null );

            if ( ACTION_CALCULATE_COST.equalsIgnoreCase( action ) )
            {
                boolean success = false;
                try
                {
                    UpdateViewCostDAO.calculateCost( null );
                    success = true;
                }
                catch ( ScalarException se )
                {
                    se.printStackTrace();
                    errors.put ("Could not Calculate Cost", null);
                    success = false;
                }
                if( success )
                {
                    info.put ( "Cost calculations successfully done", null );
                }
            }
            request.setAttribute( "baseProductsList", baseProductsList );
            request.setAttribute( "reportType", DUMP_REPORT_INVENTORY_COST_ACTION );
            forward = "inventoryCostSearch";
        }
        if ( ! info.isEmpty () )
        {
            request.setAttribute ( SessionKeys.INFO_MESSAGES, info );
        }
        if( ! errors.isEmpty () )
        {
            request.setAttribute ( ERROR_MESSAGES, errors );
        }

        return mapping.findForward( forward );
    }
}
